import { fromJS } from 'immutable'
import { SEARCHBLOG, BLOGCHANGE, ALLBLOGCHANGE, BLOGTAGCHANGE, BLOGVALUECHANGE, DELETEBLOG } from '../actionType'

const initialState = fromJS({
  edit: {
    html: '',
    text: ''
  },
  // 重新编辑的值
  value: '',
  allArticles: [],
  tags: [],
  searchList: []
})

export default (state = initialState, { type, payload }) => {
  switch (type) {
    case BLOGCHANGE:
      return state.setIn(['edit', 'html'], payload.html).setIn(['edit', 'text'], payload.text)
    case ALLBLOGCHANGE:
      return state.set('allArticles', payload)
    case BLOGTAGCHANGE:
      return state.set('tags', payload)
    case BLOGVALUECHANGE:
      return state.set('value', payload)
    case DELETEBLOG:
      // 'toJS' is not exported from 'immutable'.
      // const newState = state.toJS()//转为可变
      // const modifyArt = newState.allArticles.filter(item => item._id !== payload)
      // return fromJS({ ...newState, allArticles: modifyArt })
      // 拿出来改了之后再还回去
      const allArticles = state.get("allArticles").filter(item => item._id !== payload);
      return state.set("allArticles", allArticles);
    case SEARCHBLOG:
      const List = state.get("allArticles")
      const l1 = List.filter(item=>{
        return item.text.indexOf(payload)>-1
      })
      const l2 = List.filter(item=>item.title.indexOf(payload)>-1)
      const l3 = List.filter(item=>item.author.indexOf(payload)>-1)
      const result=[...l1,...l2,...l3]
      return state.set('searchList', Array.from(new Set(result)))
    default:
      return state
  }
}
